package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.*;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.sun.xml.bind.v2.TODO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    // 发送短信
    @Override
    public void sendMsg(String phone) {
        //生成随机的六位数
        String code = RandomUtil.randomNumbers(6);
        code ="123"; //TODO 开发期间验证码写死
        //发送短信
        //smsTemplate.sendSms(phone,code); //TODO  开发期间不发送短信
        //将验证码存入redis 用于查询验证
        redisTemplate.opsForValue().set(Constant.USER_CODE+phone,code, Duration.ofSeconds(300));

    }
    // 登陆
    @Override
    public ResultInfo login(String phone, String code) {
        // 验证验证码
        // redis code
        String codeFromRedis = (String) redisTemplate.opsForValue().get(Constant.USER_CODE + phone);
        // compare
        if (!StrUtil.equals(code,codeFromRedis)){
            // code error
            throw new CustomException("验证码不正确");
        }
        // 根据手机号查询数据库mysql
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
        qw.eq(User::getPhone,phone);
        User user = userMapper.selectOne(qw);
        // 拿到user判断状态是否禁用
        if (user ==null){  // 说明是新用户，帮你注册
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }else { //老用户
            if (user.getStatus() != 1){//禁用的用户
                throw new CustomException("您的账号已被冻结，请联系商家处理...");
            }
        }
        //登陆成功
        //制作jwt 返回
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);
        //token存redis
        redisTemplate.opsForValue().set("phone:"+user.getPhone(),user,Duration.ofDays(1));
        // 清理验证码
        redisTemplate.delete(Constant.USER_CODE+phone);
        // return token
        return ResultInfo.success(token);
    }
}
